<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\admin\validate\RoleValidate;
use Exception;
use think\facade\Db;
use think\facade\Log;
use think\Request;

/**
 * @note    角色
 * @author  liujian
 * Class Role
 * @package app\admin\controller
 * @Create  Date : 2021年04月01日 下午1:57:18
 */
class Role extends Base
{
    /**
     * @OA\Get(path="/role/list",
     *   tags={"角色管理"},
     *   summary="角色列表",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *   @OA\Parameter(name="page", in="query", description="页码", @OA\Schema(type="int", default="1")),
     *   @OA\Parameter(name="page_size", in="query", description="行数", @OA\Schema(type="int", default="10")),
     *   @OA\Parameter(name="search", in="query", description="关键词", @OA\Schema(type="string", default="")),
     *   @OA\Parameter(name="start_time", in="query", description="开始时间", @OA\Schema(type="string", default="")),
     *   @OA\Parameter(name="end_time", in="query", description="结束时间", @OA\Schema(type="string", default="")),
     *   @OA\Parameter(name="status", in="query", description="状态 1正常 2冻结 0所有", @OA\Schema(type="int", default="0")),
     *   @OA\Response(
     *      response=200,
     *      description="The Member",
     *      @OA\JsonContent(type="object",
     *          @OA\Property(property="msg", type="string"),
     *          @OA\Property(property="code", type="integer", default="200"),
     *          @OA\Property(property="data", type="object",
     *               @OA\Property(property="list", type="object",description="列表,具体值参考详情"),
     *          ),
     *      ),
     *   ),
     * )
     */
    public function list()
    {
        //
        $where_search = "";
        $where = [];
        if (!empty(input("search"))) {
            $where_search = 'role.name like "%' . input("search") . '%"';
        }
        if (!empty(input("status"))) {
            $where[] = ['role.status', '=', input("status")];
        }
        if (!empty(input("start_time")) && !empty(input("end_time"))) {
            $where[] = ['role.create_time', '<', input("end_time")];
            $where[] = ['role.create_time', '>', input("start_time")];
        }
        $list = Db::name("role")
            ->where($where)
            ->where($where_search)
            ->select()->toArray();
        return $this->jsonSuccessData("获取成功", $list);
    }

    /**
     * @OA\Post(path="/role/save",
     *   tags={"角色管理"},
     *   summary="角色添加/修改",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *     @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="角色ID", property="id", type="int", default=""),
     *           @OA\Property(description="角色名称", property="name", type="string", default=""),
     *           @OA\Property(description="状态 1正常 2冻结", property="status", type="int", default="1"),
     *           required={"name", "status"})
     *       )
     *     ),
     *   @OA\Response(
     *      response=200,
     *      description="The Member",
     *      @OA\JsonContent(type="object",
     *          @OA\Property(property="msg", type="string"),
     *          @OA\Property(property="code", type="integer", default="200"),
     *          @OA\Property(property="data", type="object",
     *          ),
     *      ),
     *   ),
     * )
     */
    public function save(Request $request)
    {
        $id = input('id');
        //
        // 启动事务
        Db::startTrans();
        try {
            $update_data = array(
                'name'        => input("name"),
                'status'      => input("status"),
                'update_time' => date("Y-m-d H:i:s")
            );

            validate(RoleValidate::class)->check($update_data);

            if ($id) {
                $result = Db::name("role")->where('id', $id)->update($update_data);
                if (!$result) throw new Exception("操作失败");

                if (!empty(input("power_ids"))) {
                    Db::name("role_power")->where("role_id", $id)->delete();
                }

                addAdminLog("修改角色$id" . "信息为" . json_encode($update_data), '修改角色信息');
            } else {
                $update_data['create_time'] = date("Y-m-d H:i:s");
                //
                $result = Db::name("role")->insert($update_data);
                if (!$result) throw new Exception("操作失败");
                $id = Db::name("role")->getLastInsID();

                addAdminLog("添加角色$id" . "信息为" . json_encode($update_data), '添加角色信息');
            }
            if (!empty(input("power_ids"))) {
                $power_ids = explode(",", input("power_ids"));
                $insert_list = [];
                for ($i = 0; $i < count($power_ids); $i++) {
                    $insert_list[] = ['role_id' => $id, 'power_id' => $power_ids[$i]];
                }
                // 添加角色角色表
                $result = Db::name("role_power")->insertAll($insert_list);
                if (!$result) throw new Exception("操作失败");
            }

            // 提交事务
            Db::commit();
            return $this->jsonSuccessData("操作成功");
        } catch (Exception $e) {
            Log::record('【角色】' . $e->getMessage() . $e->getFile() . $e->getLine());
            // 回滚事务
            Db::rollback();
            return $this->jsonFailData($e->getMessage());
        }
    }

    /**
     * @OA\Post(path="/role/delete",
     *   tags={"角色管理"},
     *   summary="角色删除",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *     @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="ID", property="id", type="int", default=""),
     *           required={"id"})
     *       )
     *     ),
     *   @OA\Response(
     *      response=200,
     *      description="The Member",
     *      @OA\JsonContent(type="object",
     *          @OA\Property(property="msg", type="string"),
     *          @OA\Property(property="code", type="integer", default="200"),
     *          @OA\Property(property="data", type="object",
     *          ),
     *      ),
     *   ),
     * )
     */
    public function delete($id)
    {
        //
        $result = Db::name("role")->where('id', 'in', $id)->delete();
        if ($result) {
            // 删除角色角色表
            Db::name("admin_role")->where("role_id", $id)->delete();
            // 删除角色角色表
            Db::name("role_power")->where("role_id", $id)->delete();
            addAdminLog("删除角色$id" . "角色信息：" . json_encode(Db::name("role")->where('id', 'in', $id)->select()->toArray()), '删除角色');
            return $this->jsonSuccessData("操作成功");
        } else {
            return $this->jsonFailData("操作失败");
        }
    }

    /**
     * @OA\Get(path="/role/read",
     *   tags={"角色管理"},
     *   summary="角色详情",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *   @OA\Parameter(name="id", in="query", description="角色ID", @OA\Schema(type="int", default="1")),
     *   @OA\Response(
     *       response=200,
     *       description="The Member",
     *       @OA\JsonContent(type="object",
     *           @OA\Property(property="msg", type="string"),
     *           @OA\Property(property="code", type="integer", default="200"),
     *           @OA\Property(property="data", type="object",
     *               @OA\Property(property="id", type="integer", description="ID"),
     *               @OA\Property(property="name", type="string", description="角色名称"),
     *               @OA\Property(property="status", type="integer", description="角色状态 1正常2冻结"),
     *               @OA\Property(property="update_time", type="string", description="更新时间"),
     *               @OA\Property(property="create_time", type="string", description="创建时间"),
     *           ),
     *       ),
     *    ),
     * )
     */
    public function read($id)
    {
        //
        $info = Db::name("role")->where('id', $id)->find();
        $power_ids = Db::name("role_power")->where("role_id", $id)->column("power_id");
        $power_list = Db::name("power")->where("id", "in", $power_ids)->select()->toArray();
        $power_list = recursion($power_list);
        return $this->jsonSuccessData("操作成功", [
            'info'       => $info,
            'power_list' => $power_list
        ]);
    }

}
